<?php
        require 'UserRepository.php';
        require 'User.php';
        require 'Message.php';
        require 'MessageRepository.php';
        require 'database.inc.php';
        require 'checkPrivileges.php';
        require 'updateChatUser.php';
        require_once('smarty3/Smarty.class.php');
        require_once('smarty3/SmartyValidate.class.php');
        
$smarty = new Smarty();
if(empty($_POST)) {
    
    SmartyValidate::connect($smarty, true);    
    SmartyValidate::register_validator('passwordLength','pass:4:-1','isLength');
    SmartyValidate::register_validator('passwordMatch','pass:pass2','isEqual');     
    $smarty->assign('oldPasswordMessage','');
    $smarty->assign('message','');
    $smarty->assign('username', htmlspecialchars($_SESSION['username']));    
    $smarty->display('settings.tpl');
} else {
    
    SmartyValidate::connect($smarty);
    $userRepository =  new UserRepository();                
    if (!$userRepository->checkUser($db, $_SESSION['username'], sha1($_POST['oldPassword']))) {
        $smarty->assign('oldPasswordMessage','Enter your old password');
        $smarty->assign('username', htmlspecialchars($_SESSION['username']));
        $smarty->assign('message','');
        $smarty->display('settings.tpl');   
    }
    else if(SmartyValidate::is_valid($_POST)) {
    
        //SmartyValidate::disconnect();
        
        
        $userRepository =  new UserRepository();                
        $user = $userRepository->getUser($db, $_SESSION['username']);        
        $editedUser = new User($user[0]['ID'], $user[0]['Username'],sha1($_POST['pass']),$user[0]['Email'], $user[0]['Name'],$user[0]['Surname']);
        $userRepository->editUser($db,$editedUser);
        updateChatUser($user[0]['Username'], $_POST['pass']);
        $smarty->assign('oldPasswordMessage','');
        $smarty->assign('message','Password changed succesfully!');
        $smarty->assign('username', htmlspecialchars($_SESSION['username']));
        $smarty->display('settings.tpl');        
    } else {
        // error, redraw the form
        $smarty->assign('oldPasswordMessage','');
        $smarty->assign('username', htmlspecialchars($_SESSION['username']));
         $smarty->assign('message','');         
        $smarty->display('settings.tpl');
        
    }
}

       
?>
